import os.path

from sourceEditor import Editor
from utils.eventHandler import EventHandler, EventArgs

class Document:  
  def __init__(self, filename):
    self._filename = ''
    self._editor = None
    self._owner = None
    
    if os.path.exists(filename):
      self._filename = filename
    else:
      self._filename = ''

    self._fileNameChangedEventHandler = EventHandler()
      
  def setOwner(self, owner):
    self._owner = owner
    if self._owner is None and not self._editor is None:
      self._editor = None

  def getEditor(self):
    if self._owner is None:
      return None

    if self._editor is None:
      self._editor = Editor(self._owner, self)
      self._editor.openFile()
    return self._editor

  def getFilename(self):
    return self._filename

  def setFilename(self, filename):
    if not filename is None and filename != '':
      oldname = self._filename
      self._filename = filename
      self.onFilenameChanged(oldname, filename)

  def saveFile(self):
    if self._filename == '':
      return False
    
    editor = self.getEditor()
    if editor is None:
      return False

    return editor.saveFile()

  # -- Event Handler -------------------------------------------------------
  def fileNameChangedEventHandler(self, handler):
    self._fileNameChangedEventHandler.add(handler)
  def onFilenameChanged(self, oldname, filename):
    eventArgs = EventArgs((oldname, filename))
    self._fileNameChangedEventHandler.invoke(self, eventArgs)
